package com.wxl.common.adapter

import android.widget.RadioButton
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.wxl.common.R
import com.wxl.common.bean.ReportBean

/**
 * create file time : 2021/4/6
 * create user : wxl
 * subscribe :
 */
class ReportAdapter : BaseQuickAdapter<ReportBean, BaseViewHolder> {

    private var radioReport: ReportBean? = null
    private var position: Int = -1

    constructor() : super(R.layout.item_report_layout, ReportBean.getReportData()) {
        setOnItemClickListener { adapter, view, position ->
            notifyCheckedChanged(position)
        }
    }


    override fun convert(helper: BaseViewHolder, item: ReportBean?) {
        item?.let {
            helper.setText(R.id.reportItemText, it.text)
            val radioButton = helper.getView<RadioButton>(R.id.reportItemRadio)
            radioButton.isChecked = it.isCheck
            radioButton.setOnCheckedChangeListener { buttonView, isChecked ->
                radioButton.postDelayed(Runnable {
                    if(isChecked){
                        if(!it.isCheck){
                            notifyCheckedChanged(helper.adapterPosition)
                        }
                    }
                },100)
            }
        }
    }

    private fun notifyCheckedChanged(position:Int){
        if (this.position != -1) {
            data[this.position].isCheck = false
            notifyItemChanged(this.position)
        }
        this.position = position
        this.radioReport = data[position]
        data[this.position].isCheck = true
        notifyItemChanged(this.position)
    }


    fun getReport(): ReportBean? {
        return radioReport
    }
}